import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter } from "vue-router";

PromiseRef.lasterror = function (e) {
  console.error(e);
  ElMessage({
    type: 'error',
    message: e.message || JSON.stringify(e),
  })
}

export default function Http() {
  const $http = axios.create({ baseURL: "/" });
  $http.interceptors.request.use(function (request) {
    // 请求头，headers 信息
    request.headers['X-Requested-With'] = 'XMLHttpRequest'
    request.headers['Authorization'] = `Bearer ${$.cache.token}`
    return request;
  });

  $http.interceptors.response.use(function (response) {
    if (response.headers['content-type'].indexOf('application/json') >= 0) {
      const res = response.data;
      if (res.code === 0) {
        return Promise.resolve(res);
      }
      switch (res.code) {
        case 3001:
          $.cache.token = '';
          window.location.reload();
          break;
        default:
          return Promise.reject(res);
      }
    }
    return Promise.reject({ code: 1, message: "未定义的返回值" });
  }, function (error) {
    console.log(error);
    return Promise.reject({ code: 1, message: "网络错误，请稍后再试" });
  });


  return Object.assign($http, {
    loading(method) {
      let that = this;
      let loadingInstance = ElLoading.service({ fullscreen: true });
      return function (url, params, config) {
        return that[method](url, params, Object.assign({ loadingInstance }, config)).finally(r => (loadingInstance.close(), r));
      }
    },
    getLoading(url, params, config) {
      return this.loading('get')(url, params, config)
    },
    postLoading(url, params, config) {
      return this.loading('post')(url, params, config)
    },
    get(url, params, config) {
      return PromiseRef.resolve($http(Object.assign({
        url,
        method: "get",
        params
      }, config)));
    },
    post(url, data, config) {
      return PromiseRef.resolve($http(Object.assign({
        url,
        method: "post",
        data
      }, config)))
    },
    upload(url, file, data = {}, config = {}) {
      var headers = { 'Content-Type': 'multipart/form-data' };
      if (file instanceof FormData) {
        var forms = file;
      } else {
        var forms = new FormData();
        for (const key in data) {
          if (data.hasOwnProperty(key)) {
            forms.append(key, data[key]);
          }
        }
        forms.append('file', file);
      }

      return PromiseRef.resolve($http(Object.assign({
        url,
        method: "post",
        data: forms
      }, { ...config, headers })));
    },
  });
}
